package com.dragon.flow.utils;

import org.apache.commons.lang.StringUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @title:
 * @author: bruce.liu
 * @since: 2024/9/6 10:45
 */
public class LocalDateUtils {

    /**
     * 得到停留时间
     *
     * @param startTime 开始时间
     * @return
     */
    public static String geTresidenceTime(Date startTime, Date endTime) {
        StringBuffer datas = new StringBuffer("");
        if (startTime == null) {
            return null;
        }
        int i = 0;
        LocalDateTime s = startTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime e = null;
        if (endTime != null) {
            e = endTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        } else {
            e = LocalDateTime.now();
        }
        Duration duration = Duration.between(s, e);
        long days = duration.toDays();
        if (i < 2 && days > 0) {
            i++;
            datas.append(days).append(" 天 ");
        }
        long hours = duration.toHours() % 24;
        if (i < 2 && hours > 0) {
            i++;
            datas.append(hours).append(" 时 ");
        }
        long minutes = duration.toMinutes() % 60;
        if (i < 2 && minutes > 0) {
            i++;
            datas.append(minutes).append(" 分 ");
        }
        long seconds = duration.getSeconds() % 60;
        if (i < 2 && seconds > 0) {
            i++;
            datas.append(seconds).append(" 秒 ");
        }
        if (StringUtils.isBlank(datas.toString())) {
            datas.append(0).append(" 秒 ");
        }
        return datas.toString().trim();
    }

    public static String geTresidenceTime(Date startTime) {
        return LocalDateUtils.geTresidenceTime(startTime, null);
    }
}
